<template>
  <div class="wise-form">
    <el-form ref="ruleForm" :model="object" :rules="rules" :validate-on-rule-change="false" label-width="100px"
      label-suffix=":">
      <template v-for="(item, index) in columns">
        <el-form-item :key="index" :prop="item.prop" :label="item.label" :label-width="item.labelWidth"
          :required="item.required" :rules="item.ruleArr" :error="item.error" :show-message="item.showMessage"
          :inline-message="item.inlineMessage" :size="item.size">
          <template v-if="
              ['text', 'textarea', 'password', 'url', 'hidden'].indexOf(
                item.type
              ) != -1
            ">
            <el-input v-model="object[item.prop]" :type="item.type" :placeholder="item.placeholder"
              :maxlength="item.maxlength" :minlength="item.minlength" show-word-limit clearable
              :disabled="item.disabled" :size="item.size" :prefix-icon="item.prefixIcon" :suffix-icon="item.suffixIcon"
              :rows="item.rows" :autosize="true" :name="item.prop" :readonly="item.readonly" :max="item.max"
              :min="item.min" :step="item.step" :resize="item.resize" autofocus :label="item.label" />
          </template>
          <template v-if="item.type == 'warning'">
            <div class="warning">{{ item.text }}</div>
          </template>
          <template v-if="item.type == 'number'">
            <el-input-number v-model="object[item.prop]" :min="item.min" :max="item.max" :step="item.step"
              :precision="item.precision" :label="item.lable" :placeholder="item.placeholder" :controls="false" />
          </template>
          <template v-if="item.type == 'radio'">
            <wise-radio v-model="object[item.prop]" :data-dic="item.dataDic" />
          </template>
          <template v-if="item.type == 'select'">
            <wise-select v-model="object[item.prop]" :url="item.url" :label-key="item.labelKey" :data-dic="item.dataDic"
              :value-key="item.valueKey" :filters="item.filters" :filters-obj="item.filtersObj" :obj-keys="item.objKeys"
              :disabled="item.disabled" :obj-params="item.objParams" :object="object" @on-value="setValue" />
          </template>
          <template v-if="item.type == 'select-multiple'">
            <wise-select-multiple v-model="object[item.prop]" :url="item.url" :label-key="item.labelKey"
              :data-dic="item.dataDic" :value-key="item.valueKey" :filters="item.filters" :filters-obj="item.filtersObj"
              :obj-keys="item.objKeys" :disabled="item.disabled" :object="object" />
          </template>
          <template v-if="item.type == 'file'">
            <wise-file v-model="object[item.prop]" :limit="item.limit" :upload-type="item.uploadType"
              :accept="item.accept" :fun="item.fun" :max-file-size="item.maxFileSize" :object="object"
              :desc="item.desc" />
          </template>
          <template v-if="item.type == 'area'">
            <wise-region v-model="object[item.prop]" :show-type="item.showType" :obj-keys="item.objKeys"
              :town="item.town" @on-value="setValue" />
          </template>
          <template v-if="
              ['year', 'month', 'date', 'week', 'datetime'].indexOf(
                item.type
              ) != -1
            ">
            <wise-date v-model="object[item.prop]" :type="item.type" :format="item.format"
              :value-format="item.valueFormat" :placeholder="item.placeholder" />
          </template>
          <template v-if="item.type == 'editor'">
            <wise-editor v-model="object[item.prop]" />
          </template>
          <template v-if="item.type == 'render'">
            <form-render :item="item" :object="object" :render="item.render" />
          </template>
        </el-form-item>
      </template>
      <el-form-item>
        <el-button type="primary" :disabled="loading" :loading="loading" @click="submitForm('ruleForm')">
          {{ loading ? "提交中..." : "提交" }}</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import FormRender from './formRender'
  import WiseRadio from '../components/wiseRadio'
  import WiseSelect from '../components/wiseSelect'
  import WiseFile from '../components/wiseFile'
  import WiseEditor from '../components/wiseEditor'
  import WiseDate from '../components/wiseDate'
  import WiseRegion from '../components/wiseRegion'
  import WiseSelectMultiple from '../components/wiseSelectMultiple'
  export default {
    name: 'WiseForm',
    components: {
      WiseSelectMultiple,
      WiseRegion,
      WiseDate,
      WiseEditor,
      WiseFile,
      WiseSelect,
      WiseRadio,
      FormRender
    },
    props: {
      columns: {
        type: Array,
        required: true
      },
      loading: {
        type: Boolean,
        default: false
      },
      oldObject: {
        type: Object
      }
    },
    data() {
      return {
        object: {},
        rules: {},
        typeValue: '1',
        options: [{
            value: '1',
            label: '图片'
          },
          {
            value: '2',
            label: 'URL'
          }
        ]
      }
    },
    watch: {
      oldObject(val) {
        if (val && val.id) {
          for (const key in val) {
            this.$set(this.object, key, val[key])
          }
          this.columns.forEach((item) => {
            if (item.type === 'select') {
              const o = {}
              if (item.objKeys && item.objKeys.length > 0) {
                item.objKeys.forEach((f) => {
                  o[f.key] = this.object[f.field]
                })
              }
              this.$set(this.object, item.prop, o)
            }
            if (item.type === 'area') {
              const o = {
                province: {},
                city: {},
                area: {},
                town: {}
              }
              if (item.objKeys && item.objKeys.length > 0) {
                item.objKeys.forEach((f) => {
                  o[f.key][f.value] = this.object[f.field]
                })
              }
              this.$set(this.object, item.prop, o)
            }
          })
        }
      }
    },
    mounted() {
      this.init()
    },
    methods: {
      init() {
        this.columns.forEach((item) => {
          this.$set(this.object, item.prop, item.defaultValue)
          if (item.defaultValue) {
            if (item.type === 'select') {
              let arry = []
              item.objKeys.forEach((o) => {
                arry.push({
                  field: o.field,
                  value: item.defaultValue[o.key]
                })
              })
              this.setValue(arry)
            }
          }
          item['ruleArr'] = []
          if (item.rules && item.rules.length > 0) {
            item.rules.forEach((r) => {
              if (r.validator) {
                item.ruleArr.push({
                  validator: (rule, value, callback) => {
                    r.validator(rule, value, callback, this)
                  },
                  trigger: r.trigger
                })
              } else {
                item.ruleArr.push(r)
              }
            })
          }
        })
        let column = this.columns[0]
        this.columns.splice(0, 1)
        this.columns.splice(0, 0, column)
      },
      setValue(objVal) {
        if (objVal && objVal.length > 0) {
          objVal.forEach((item) => {
            this.$set(this.object, item.field, item.value)
          })
        }
      },
      setCoordinate(coord) {
        this.object.longitude = coord.longitude
        this.object.latitude = coord.latitude
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$emit('on-submit', this.object)
          } else {
            return false
          }
        })
      },
      resetForm(formName) {
        let spaceId, entSpaceId
        if (this.object.spaceId) {
          spaceId = this.object.spaceId
        }
        if (this.object.entSpaceId) {
          entSpaceId = this.object.entSpaceId
        }
        this.$nextTick(() => {
          this.$refs[formName].resetFields()
        })
        setTimeout(() => {
          if (this.object.spaceId == undefined) {
            this.object.spaceId = spaceId
          }
          if (this.object.entSpaceId) {
            this.object.entSpaceId == entSpaceId
          }
        }, 100)

      }
    }
  }
</script>

<style lang="scss" scoped>
  .warning {
    color: #f56c6c;
  }
</style>